package com.rk.msm.controller;

import com.alibaba.excel.util.StringUtils;
import com.rk.common.result.Result;
import com.rk.msm.service.MsmService;
import com.rk.msm.util.RandomUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;

/**
 * @author :Rk.
 * @date : 2022/11/22
 */
@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 发送邮箱验证码
     *
     * @param email
     * @return
     */
    @ApiOperation(value = "发送邮箱验证码")
    @GetMapping("/sendEmail/{email}")
    public Result sendEmail(@PathVariable String email) {

        //从redis获取验证码，如果获取获取到，返回ok
        // key 手机号  value 验证码
        String code = redisTemplate.opsForValue().get(email);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        // 没有就生成验证码，
        code = RandomUtil.getSixBitRandom();
        //调用service方法，通过整合短信服务进行发送
        boolean isSend = msmService.sendEmail(email, code);
        //生成验证码放到redis里面，设置有效时间
        if (isSend) {
            redisTemplate.opsForValue().set(email, code, 3, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送邮件失败");
        }
    }


    /**
     * 发送手机验证码
     *
     * @param phone
     * @return
     */
    @ApiOperation(value = "发送手机验证码")
    @GetMapping("/sendMessage/{phone}")
    public Result sendMessage(@PathVariable String phone) {

        //从redis获取验证码，如果获取获取到，返回ok
        // key 手机号  value 验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        // 没有就生成验证码，
        code = RandomUtil.getSixBitRandom();
        //调用service方法，通过整合短信服务进行发送
        boolean isSend = msmService.sendMessage(phone, code);
        //生成验证码放到redis里面，设置有效时间 3分钟过期
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 3, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }
    }
}

